package com.yueqian.epidemic;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
// 扫描 com.yueqian.epidemic.mapper 包中的 *.java文件
@MapperScan(basePackages ="com.yueqian.epidemic.mapper")
public class MybatisConfig {
    private Logger logger = Logger.getLogger(MybatisConfig.class);

    /**
     * 配置数据源
     */
    @Bean(name = "dataSource", destroyMethod = "close")
    public BasicDataSource basicDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        // 配置数据库的驱动
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        // 数据库连接url地址 (jdbc:mysql://localhost:3306/epidemic)
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/epidemic?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai");
        // 连接数据库的登录账号
        dataSource.setUsername("root");
        // 登录密码
        dataSource.setPassword("root123");

        // 连接池的相关配置
        dataSource.setInitialSize(3);
        dataSource.setMaxActive(50);
        dataSource.setMaxIdle(1);
        // 毫秒
        dataSource.setMaxWait(4000);
        // 设置是否是自动提交事务，false：手动提交
        dataSource.setDefaultAutoCommit(false);

        return dataSource;
    }

    /**
     * 创建会话对象
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 关联数据源
        factoryBean.setDataSource(dataSource);

        // 设置包的别名
        factoryBean.setTypeAliasesPackage("com.yueqian.epidemic.beans");
        // 设置实体类中的属性名和数据表中字段列名骆峰命名
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);

        factoryBean.setConfiguration(configuration);
        SqlSessionFactory factory = null;
        try {
            // 得到SqlSessionFactory对象
            factory = factoryBean.getObject();
        } catch (Exception e) {
            logger.error("配置SqlSessionFactory时报错，" + e.getMessage());
        }
        return factory;
    }


}
